from rest_framework import serializers
from api.models import SysMenu

class UserMenuSerializer(serializers.ModelSerializer):
    # 自定义字段映射
    name = serializers.CharField(source='menu_name')
    hidden = serializers.SerializerMethodField()
    redirect = serializers.SerializerMethodField()
    alwaysShow = serializers.SerializerMethodField()
    meta = serializers.SerializerMethodField()
    children = serializers.SerializerMethodField()

    class Meta:
        model = SysMenu
        fields = ['name', 'path', 'hidden', 'redirect', 'component', 
                 'alwaysShow', 'meta', 'children']

    def get_hidden(self, obj):
        return obj.visible == '1'  # 如果visible是'1'表示隐藏

    def get_redirect(self, obj):
        return "noRedirect"  # 固定值，可根据业务调整

    def get_alwaysShow(self, obj):
        return obj.menu_type == 'M'  # 目录类型总是显示

    def get_meta(self, obj):
        return {
            "title": obj.menu_name,
            "icon": obj.icon if obj.icon != '#' else '',
            "noCache": obj.is_cache == 1,  # is_cache为1表示不缓存
            "link": None  # 可根据业务调整
        }

    def get_children(self, obj):
        # 获取所有子菜单
        children = SysMenu.objects.filter(parent_id=obj.menu_id)
        serializer = UserMenuSerializer(children, many=True)
        return serializer.data